package com.atguigu.vod.Utils.aliyunVodUtils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.atguigu.vod. Utils.ConstanPropertiesVodUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;
@Slf4j
public class PutUploadUtils {

    //上传阿里云
    public static String aliyunPutUpload (MultipartFile file) {
        //您的AccessKeyId
        String accessKeyId = ConstanPropertiesVodUtils.KEY_ID;
        //您的AccessKeySecret
        String accessKeySecret = ConstanPropertiesVodUtils.KEY_SECRET;
        log.info("开始上传视频到阿里云，" + "accessKeyId:" + accessKeyId);
        //需要上传到VOD的本地视频文件的完整路径，需要包含文件扩展名
        String fileName = file.getOriginalFilename();

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
         fileName = uuid + file.getOriginalFilename();
        log.info( "localFile:" + fileName);

        String title = fileName.substring(0,fileName.lastIndexOf("."));

        try{
            InputStream inputStream = file.getInputStream();
            //初始化vod客户端
            DefaultAcsClient Client = InitObject.initVodClient(accessKeyId,accessKeySecret);

            //创建一个相应的对象
            CreateUploadVideoResponse uploadVideo = createUploadVideo(Client,fileName,title);
            // 执行成功会返回VideoId、UploadAddress和UploadAuth
            String videoId = uploadVideo.getVideoId();

            //解析拿到结果对象
            JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(uploadVideo.getUploadAuth()));
            JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(uploadVideo.getUploadAddress()));

            // 使用UploadAuth和UploadAddress初始化OSS客户端
            OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);
            uploadLocalFile(ossClient, uploadAddress, inputStream);
            System.out.println("Put local file succeed, VideoId : " + videoId);
            return videoId;
        }catch (Exception e){
            System.out.println("Put local file fail, ErrorMessage : " + e.getLocalizedMessage());
        }
        return null;
    }


    private static String decodeBase64(String data) {
        return new String(Base64.decodeBase64(data));
    }

    //初始化VOD客户端、需要注意接入服务地址

//    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
//        // 根据点播接入服务所在的Region填写，例如：接入服务在上海，则填cn-shanghai；其他区域请参见存储说明。
//        String regionId = "cn-shanghai";
//        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
//        DefaultAcsClient client = new DefaultAcsClient(profile);
//        return client;
//    }
    //创建视频上传结果对象
    //设置名称等
    private static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient, String fileName,String title) throws ClientException, com.aliyuncs.exceptions.ClientException {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setFileName(fileName);
        request.setTitle(title);
        //设置请求超时时间
        request.setSysReadTimeout(1000);
        request.setSysConnectTimeout(1000);
        return vodClient.getAcsResponse(request);
    }

    //初始OSS客户端
    private static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) throws JSONException {
        String endpoint = uploadAddress.getString("Endpoint");
        String accessKeyId = uploadAuth.getString("AccessKeyId");
        String accessKeySecret = uploadAuth.getString("AccessKeySecret");
        String securityToken = uploadAuth.getString("SecurityToken");
        return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    }
    //上传文件
    private static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, InputStream inputStream) throws JSONException {
        String bucketName = uploadAddress.getString("Bucket");
        String objectName = uploadAddress.getString("FileName");
//        File file = new File(localFile);
        ossClient.putObject(bucketName, objectName, inputStream);
    }

}
